var app = getApp();
Page({
  data: {
    showModalStatus: false, //遮罩层
    showcartModalStatus: false, //显示结账
    showQuan: false, //显示优惠劵
    url: {
      getShopInfo: app.url.baseUrl + "/shop/info",
      //getProduct: app.url.baseUrl + "/shop/publicfood",food
      getProduct: app.url.baseUrl + "/shop/food",
      getProductType: app.url.baseUrl + "/kind/list",
      getTypeProduct: app.url.baseUrl + "/shop/typeProduct1",
      getDiscount: app.url.baseUrl + "/shop/discount",
      xindent: app.url.baseUrl + "/indent/lowerIndent",
      getTableNoInfo: app.url.baseUrl + "/shop/tableNum",
      connectionOrEsc: app.url.baseUrl + "/shop/connectionOrEsc",
      isConnection: app.url.baseUrl + "/shop/isCollection",
      payS: app.url.baseUrl + "/indent/paySuccess",
      isExistsCoupon: app.url.baseUrl + "/my/isExistsCoupon",
    },
    shopInfo:{},//店铺信息
    shopId: 0, //店表ID
    tableNoName: 0,//桌号
    currTypeIndex: 0,//菜品类型
    productType: [],
    showProducts: [],//菜品列表
    shoppingCart: {},//已点菜品,数量,价格,是否折扣
    productTypeNum: 0,//产品类型种类
    totalPrice: "0.00",  //打折前价格
    discountPrice: "0.00",  //打折后价格
    isExists: false,
    isConection: false, //是否收藏该店铺
    istj: false,  //是否提交
    productLogo: '',
    money: '',
    isEnough: false
  },
  onShow: function () {
    var obj = app.param.scanCallCoupon
    if (obj == null || obj.money == null)
      return
    var discountPrice = this.data.totalPrice - obj.money
    this.setData({ money: obj.money })
    this.setData({ isEnough: true })
    console.log(this.data.isEnough)
    discountPrice = discountPrice.toFixed(2)
    if (discountPrice < 0)
      discountPrice = 0.00
    this.setData({ discountPrice: discountPrice })
  },
  onLoad: function (options) {
    var that = this;
    var shopId = options.shopId
    var tableId = options.tableId
    //服务
    // shopId = "8861cfd7b09b4927ab50589bb8d044fa"
    // tableId = "7f757426b0a4449cae059cae06ae19e1"
    //客户
    //乾路测试店铺
    // shopId = "871ec411a4344df28367eb4281b1affc"
    // tableId = "96e38be7101148ab812ebdb458547fcf"
    //万忠的味道
    // shopId = "a50be37c60ec4f0d94d557e7162cf664"
    // tableId = "21deb304d95e44ff934d487eb6d7aa2d"
    //本地
    // shopId = "871ec411a4344df28367eb4281b1affc"
    // tableId = "01dc7312e8ee491383aec21f73dc7f6b"
    console.log("商铺编号" + shopId)
    console.log("商铺桌号" + tableId)
    this.setData({ shopId: shopId, tableId: tableId })
    this.getShopInfo(shopId)  //获取店铺信息
    //获取菜品类别
    app.ajax(this.data.url.getProductType, { id: this.data.shopId }, function (res) {
      that.setData({ productType: res.data.data })
    })
    //获取菜品
    this.getProduct()
    //是事收藏该店铺
    this.getIsConnection()
    //获取桌号信息
    this.getTableNoInfo(tableId, shopId)
  },
  //是否收藏
  getIsConnection(obj) {
    var that = this;
    app.ajax(this.data.url.isConnection, { shopId: this.data.shopId }, function (res) {
      var d = res.data
      if (d.data) {
        that.setData({ isConection: d.data })
      }
    })
  },
  //获取店铺信息
  getShopInfo: function (obj) {
    var data = { id: obj };
    var that = this;
    app.ajax(this.data.url.getShopInfo, data, function (res) {
      if (res.data.code!=2000){
        that.setData({ shopInfo: null });
        wx.redirectTo({
          url: 'tabledisable/tabledisable?type=1',
        })
        return
      }
      var shopInfo = res.data.data;
      that.setData({ shopInfo: shopInfo });
    })
  },
  //桌号信息
  getTableNoInfo: function (obj, obj1) {
    var data = { id: obj, shopId: obj1 };
    console.log(data);
    var that = this;
    app.ajax(this.data.url.getTableNoInfo, data, function (res) {
      var talbeNoInfo = res.data.data;
      console.log("桌号返回数据start")
      console.log(res.data)
      console.log(talbeNoInfo)
      console.log("桌号返回数据end")
      if (talbeNoInfo == null || talbeNoInfo == 'null') {
        wx.redirectTo({
          url: 'tabledisable/tabledisable',
        })
        return
      }
      that.setData({ tableNoName: talbeNoInfo.code + app.getRandomChar(0) });
    })
  },
  //获取产品
  getProduct: function () {
    var that = this;
    var currTypeIndex = this.data.currTypeIndex;
    var shopId = this.data.shopId;

    var url = this.data.url.getProduct;
    var data = { id: this.data.shopId }
    if (currTypeIndex != '0') {
      url = this.data.url.getTypeProduct;
      data = { productType: currTypeIndex, ascriptionShop: shopId }
    }
    app.ajax(url, data, function (res) {
      var data = res.data.data;
      var shoppingCart = that.data.shoppingCart
      for (var i = 0; i < data.length; i++) {
        var obj = data[i]
        if (obj.detail == null)
          obj.detail = ""
        if (obj.monthSoldNum == null)
          obj.detail = 0
        var shopProduct = shoppingCart[obj.id]
        if (shopProduct != null)
          obj.shopNum = shopProduct.shopNum
        else
          obj.shopNum = 0
      }
      that.setData({ showProducts: res.data.data });
    })
  },
  //收藏或取消
  faverite_Tap: function () {
    var b = !this.data.isConection
    var that = this;
    app.ajax(this.data.url.connectionOrEsc, { shopId: this.data.shopId, isConnection: b }, function (res) {
      if (res.data.code == 2000) {
        that.setData({
          isConection: b
        });
      }
    })
  },
  //选择产品类型
  selectType: function (event) {
    var index = event.currentTarget.dataset.modelidx;
    this.setData({ currTypeIndex: index });
    this.getProduct();
  },
  //修改已点菜品
  editShopingCart: function (e) {
    var d = e.currentTarget.dataset
    console.log(d)
    var isAdd = d.is_add
    var id = d.pid
    var name = d.pname
    var productLogo = d.productlogo;
    var producttype = d.producttype
    var price = parseFloat(d.price)
    var isDiscount = d.is_discount == null ? 0 : d.is_discount
    var shoppingCart = this.data.shoppingCart
    var sp = shoppingCart[id];
    var curNum = null;
    if (sp == null) { //没有点过菜
      if (isAdd == "1") { //加菜
        shoppingCart[id] = { id: id, name: name, price: price, productType: producttype, isDiscount: isDiscount, shopNum: 1, totalPrice: price, productLogo: productLogo }
        curNum = 1;
      } else  //不存在还要点减号
        return
    } else {//已点菜
      if (isAdd == "1") { //加数量
        sp.shopNum += 1
        curNum = 1;
      } else {//减数量
        if (sp == null) { //减数量的时候是空的
          return
        } else if (sp.shopNum == 1) { //减数量的时候已点的菜里面数量为1
          shoppingCart[id] = null
          sp == null
          curNum = -1;
        } else {
          sp.shopNum -= 1
          curNum = -1;
        }
      }
      if (sp != null)
        sp.totalPrice = (parseFloat(sp.price) * parseInt(sp.shopNum)).toFixed(2)
    }
    var curTotalPrice = parseFloat(this.data.totalPrice)
    this.setData({
      shoppingCart: shoppingCart,
      totalPrice: (curTotalPrice + price).toFixed(2),
      productLogo: productLogo
    });
    var showProduct = this.data.showProducts;
    var showProdeuctLen = showProduct.length;
    //更新界面数量
    for (var i = 0; i < showProdeuctLen; i++) {
      var obj = showProduct[i];
      if (obj.id == id)
        obj.shopNum += curNum;
    }
    console.log(sp)
    this.setData({ showProducts: showProduct });
  },

  //结账时+-号
  countGood: function (e) {
    var that = this;
    var d = e.currentTarget.dataset
    console.log(d)
    var index = d.index;
    var num = d.num;
    var shoppingCart = this.data.shoppingCart[index]
    var curTotalPrice = parseFloat(this.data.totalPrice)
    if (num > 0) {//+数量
      shoppingCart.shopNum = shoppingCart.shopNum + 1
      curTotalPrice = (curTotalPrice + d.price).toFixed(2)
    } else { //-数量
      if (shoppingCart.shopNum > 1) {

        shoppingCart.shopNum = shoppingCart.shopNum - 1
        curTotalPrice = (curTotalPrice - d.price).toFixed(2)
      } else {
        curTotalPrice = (curTotalPrice - d.price).toFixed(2)
        this.data.shoppingCart[index] = null
        shoppingCart.shopNum = 0
        //当没有菜品的时候隐藏结算 
        var isExists = false;
        for (var key in this.data.shoppingCart) {
          if (this.data.shoppingCart[key] != null)
            isExists = true;
        }
        if (!isExists) {
          this.hideCartModal();
        }
      }
    }
    var showProduct = this.data.showProducts;
    var showProdeuctLen = showProduct.length;
    //更新界面数量
    for (var i = 0; i < showProdeuctLen; i++) {
      var obj = showProduct[i];
      if (obj.id == index)
        obj.shopNum = shoppingCart.shopNum;
    }
    app.ajax(this.data.url.getDiscount, { id: this.data.shopId }, function (res) {
      var discount = res.data.data;
      discount = discount == null ? 1 : parseFloat(discount);
      //discount = 0.90;
      var discountPrice = 0.00;

      var markProductType = []  //标记类型
      var existsDip = false //是否存在折扣商品
      that.data.productTypeNum = 0
      //计算折扣价
      //obj = shoppingCart;
      // if (obj != null) {
      //   var discountPrice = parseFloat(discountPrice)
      //   if (obj.isDiscount != null && obj.isDiscount == '1') {
      //     if (num > 0) {
      //       discountPrice = ((discountPrice + d.price) * discount).toFixed(2)
      //     } else {
      //       discountPrice = ((discountPrice - d.price) * discount).toFixed(2)
      //     }
      //     existsDip = true
      //   } else {
      //     if (num > 0) {
      //       discountPrice = (discountPrice + d.price).toFixed(2)
      //     } else {
      //       discountPrice = (discountPrice - d.price).toFixed(2)
      //     }
      //   }

      //   //计算产品类型数量
      //   if (obj.productType != null && obj.productType != "") {
      //     if (markProductType[obj.productType] == null) {
      //       that.data.productTypeNum += 1
      //       markProductType[obj.productType] = 1
      //     }
      //   }
      // }

      var shoppingCart = that.data.shoppingCart;
      //计算折扣价
      for (var obj in shoppingCart) {
        var objid = obj;
        obj = shoppingCart[obj];
        if (obj != null) {
          var objPrice = parseFloat(obj.price)
          var shopNum = parseInt(obj.shopNum)
          objPrice = (shopNum * objPrice)
          if (obj.isDiscount != null && obj.isDiscount == '1') {
            objPrice = objPrice * discount;
            existsDip = true
          }
          discountPrice += objPrice

          //计算产品类型数量
          if (markProductType[objid] == null) {
              that.data.productTypeNum += 1
              markProductType[objid] = 1
            }
        }
      }

      //不存在折扣商品才去查优惠劵
      if (!existsDip) {
        app.ajax(that.data.url.isExistsCoupon, { productTypeCount: that.data.productTypeNum, lowestPrice: that.data.totalPrice }, function (res) {
          var d = res.data.data
          if (d != null && d == true) {
            that.setData({ showQuan: true })
          } else
            that.setData({ showQuan: false })

          if (that.data.isEnough) {
            if (!that.data.showQuan) {
              that.setData({ isEnough: false })
              discountPrice = (parseFloat(discountPrice) + parseFloat(that.data.money)).toFixed(2)
              that.setData({ discountPrice: discountPrice })
            }
          }
        })
      }
      that.setData({ discountPrice: discountPrice.toFixed(2)})
    })
    this.setData({ showProducts: showProduct });
    var totalPrice = null
    if (d.price != null) {
      totalPrice = (parseFloat(d.price) * parseInt(shoppingCart.shopNum)).toFixed(2)
      shoppingCart.totalPrice = parseFloat(totalPrice)
    }
    console.log(curTotalPrice + parseFloat(totalPrice)),
      this.setData({ shoppingCart: this.data.shoppingCart, totalPrice: curTotalPrice });
  },
  showModal: function () {
    // 显示遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
      showModalStatus: true
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export()
      })
    }.bind(this), 200)
  },
  clickbtn: function () {
    if (this.data.showModalStatus) {
      this.hideModal();
    } else {
      this.showModal();
    }
  },
  hideModal: function () {
    // 隐藏遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export(),
        showModalStatus: false
      })
    }.bind(this), 200)
  },
  showCartModal: function () {
    // 显示遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
      showcartModalStatus: true
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export()
      })
    }.bind(this), 200)
  },
  //结算
  settlement: function () {
    var shoppingCart = this.data.shoppingCart;
    var b = false;
    //是否点菜
    for (var c in shoppingCart) {
      if (shoppingCart[c] != null) {
        b = true
        break
      }
    }
    if (!b) {
      wx.showToast({
        title: '您还没有选择菜品',
      })
      return
    }
    var that = this;

    //获取折扣
    app.ajax(this.data.url.getDiscount, { id: this.data.shopId }, function (res) {
      var discount = res.data.data;
      discount = discount == null ? 1 : parseFloat(discount);
      //discount = 0.90;
      var discountPrice = 0.00;

      var markProductType = []  //标记类型
      var existsDip = false //是否存在折扣商品
      that.data.productTypeNum = 0
      //计算折扣价
      for (var obj in shoppingCart) {
        var objid = obj;
        obj = shoppingCart[obj];
        if (obj != null) {
          var objPrice = parseFloat(obj.price)
          var shopNum = parseInt(obj.shopNum)
          objPrice = (shopNum * objPrice)
          if (obj.isDiscount != null && obj.isDiscount == '1') {
            objPrice = objPrice * discount;
            existsDip = true
          }
          discountPrice += objPrice;

          //计算产品类型数量
          if (markProductType[objid] == null) {
              that.data.productTypeNum += 1
              markProductType[objid] = 1
            }
        }
      }

      //不存在折扣商品才去查优惠劵
      if (!existsDip) {
        app.ajax(that.data.url.isExistsCoupon, { productTypeCount: that.data.productTypeNum, lowestPrice: that.data.totalPrice }, function (res) {
          var d = res.data.data
          if (d != null && d == true) {
            that.setData({ showQuan: true })
          } else
            that.setData({ showQuan: false })
        })
      }
      that.setData({ discountPrice: discountPrice.toFixed(2) })
      if (that.data.showcartModalStatus) {
        that.hideCartModal();
      } else {
        that.showCartModal();
      }
    })
  },
  //下单
  xindent: function () {
    var that = this
    if (this.data.istj) {
      wx.showToast({
        title: '不能重复提交，请稍候',
      })
      return
    }
    this.setData({ istj: true })
    var ids = [];
    var nums = [];
    for (var obj in this.data.shoppingCart) {
      var o = this.data.shoppingCart[obj];
      if (o != null) {
        ids.push(obj);
        nums.push(o.shopNum);
      }
    }

    var appObj = app.param.scanCallCoupon
    var data = {
      shopId: this.data.shopId,
      productIds: ids,
      productNums: nums,
      tno: this.data.tableNoName,
      pNumber: this.data.pNumber,
      wecharCalcAfterprice: this.data.discountPrice,
      qId: appObj == null ? '' : appObj.id
    }
    app.ajax(this.data.url.xindent, data, function (res) {
      that.setData({ istj: false })
      var d = res.data
      var ino = d.msg
      if (d.code == 2004) {
        wx.redirectTo({
          url: '../paysuccess/paysuccess?iss=1&shopId=' + that.shopId + "&tableId" + that.tableId,
        })
        return
      } else if (d.code != 2000) {
        wx.showToast({
          title: '交易异常请刷新重试',
        })
        return
      } else {
        wx.requestPayment({
          timeStamp: d.data.timeStamp,
          nonceStr: d.data.nonceStr,
          package: "prepay_id=" + d.data.packages,
          signType: d.data.signType,
          paySign: d.data.paySign,
          success: function (res) {
            app.param.scanCallCoupon = null
            console.log("支付成功，订单号为:" + ino)
            wx.redirectTo({
              url: '../paysuccess/paysuccess?iss=1&shopId=' + that.shopId + "&tableId" + that.tableId,
            })
          }, fail: function (res) {
            console.log("支付失败")
            console.log(res)
          }
        })
      }
    }, function () {
      wx.showToast({
        title: '网络异常，请稍候再试',
      })
      that.setData({ istj: false })
    })
  },
  hideCartModal: function () {
    app.param.scanCallCoupon = null
    console.log(app.param.scanCallCoupon);
    this.setData({ showQuan: false })
    // 隐藏遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export(),
        showcartModalStatus: false
      })
    }.bind(this), 200)
  },
  useCoupon() {
    wx.navigateTo({
      url: 'usecoupon/usecoupon?productTypeNum=' + this.data.productTypeNum + "&totalPrice=" + this.data.totalPrice,
    })
  },
  preImage:function(e){
    var index = e.currentTarget.dataset.index;
    var d = this.data.showProducts[index];
    if (d.isSaleOver!=1){
      wx.previewImage({
        urls: [d.productLogo],
      })
    }
  }
})

